package com.cstar.learnlang.PageControllers;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.cstar.learnlang.DataForms.FeedbackDataForm;
import com.cstar.learnlang.DataForms.SignupDataForm;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

@Controller
@RequestMapping(value={"/registerActionPost", "/signupPage"})
@SessionAttributes
public class SignupPageController {
	private static final Logger logger = LoggerFactory.getLogger(SignupPageController.class);
	@Autowired
	private JdbcTemplate jdbcRegisterInfoTemplate;
	@Autowired
	private MailSender mailSender;
	@Autowired
	private HomePageController homePageController;
	@RequestMapping(value = "/signupPage", method = RequestMethod.GET)
	public String signupPage(HttpServletRequest request,
			HttpServletResponse response,
    		HttpSession session,
			@RequestParam(value="logout", required=false) String logout, 
			@RequestParam(value="ln", required=false) String ln) {
		logger.info("signupPage");
		homePageController.ProcessLanguageSwitchAndLogout(request, response, session, ln, logout);
		session.setAttribute("pageName", "signup");
		return "signupPage";
	} // signupPage
	@RequestMapping(value="/registerActionPost", method = RequestMethod.POST)
    public ModelAndView registerActionPost(
    		HttpSession session,
    		@ModelAttribute("registerActionInfo") SignupDataForm registerActionInfo, 
    		BindingResult result) {
		logger.info("email:" + registerActionInfo.getEmail() + "password:" + registerActionInfo.getPassword());
		String sql = "SELECT COUNT(*) FROM USER_INFO WHERE EMAIL = ?";
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		ModelAndView mv = new ModelAndView ("redirect:/signupPage");
		int anyMatch = jdbcRegisterInfoTemplate.queryForInt(sql, new Object[] { registerActionInfo.getEmail() });
		if (anyMatch == 0) {
			// Create a new user
			sql = "INSERT INTO USER_INFO (EMAIL, PASSWORD_MD5) VALUES (?, ?)";
			jdbcRegisterInfoTemplate.update(sql, new Object[] { 
					registerActionInfo.getEmail(), 
					md5.encodePassword(registerActionInfo.getPassword(), "") 
			});
			session.setAttribute ("serverReturnCode", "Success:Congratulations, you have signed up! Now you can use the advanced features of the site.");
			SendEmail_SignUp (registerActionInfo.getEmail());
		} else { // email is already registered
			session.setAttribute ("serverReturnCode", "Error:Sorry, there is already a user registered with this email address. " +
		        "You can <a href='/learnlang/passwordResetPage'>reset</a> your password or <a href='/learnlang/loginPage'>log in</a>.");
		} // if
		logger.info("registerActionPost anyMatch:" + anyMatch);
        return mv;
    } // registerActionPost
	@ModelAttribute("registerActionInfo")
    public SignupDataForm getFeedbackInfoObj() {
        return new SignupDataForm();
    }
	private void SendEmail_SignUp (String email) {
		System.out.println("sign up okay sending email to " + email);
		
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo(email);
		message.setFrom("no-reply@learnlang.biz");
		message.setSubject("www.learnlang.biz account created!");
		message.setText("Congratulations, \n\nYour account has been created. Use your email "+
				"address as your login name.\n\nKind regards,\nLearn Language Team @ http://www.learnlang.biz");
		mailSender.send(message);
	}
}
